<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="150px">
      <el-form-item :label="$t('version.firmware.versionName')" prop="versionName">
        <el-input v-model="queryParams.versionName" :placeholder="$t('version.firmware.placeholder.versionName')"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item :label="$t('version.firmware.versionNumber')" prop="versionNumber">
        <el-input v-model="queryParams.versionNumber"
                  :placeholder="$t('version.firmware.placeholder.versionNumber')"
          clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <el-form-item :label="$t('version.firmware.versionType')" prop="versionType">
        <el-select v-model="queryParams.versionType" clearable size="small" style="width: 240px" :placeholder="$t('version.firmware.placeholder.versionType')">
          <el-option v-for="dict in dict.type.firmware_type"
                     :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('common.button.query')}}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{$t('common.button.reset')}}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['app:firmwareVersion:add']">{{$t('common.button.add')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['app:firmwareVersion:edit']">{{$t('common.button.edit')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['app:firmwareVersion:remove']">{{$t('common.button.remove')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['app:firmwareVersion:export']">{{$t('common.button.export')}}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="firmwareVersionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('version.firmware.versionId')" align="center" prop="versionId" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('version.firmware.versionName')" align="center" prop="versionName" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('version.firmware.versionNumber')" align="center" prop="versionNumber" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('version.firmware.versionType')" align="center" prop="versionType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.firmware_type" :value="scope.row.versionType" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('version.firmware.versionUrl')" align="center" prop="versionUrl" width="220" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('version.firmware.remark')" align="center" prop="remark" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('version.firmware.isForce')" align="center" prop="isForce">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isForce" active-value="1" inactive-value="0"
                     @change="handleForceChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column :label="$t('version.firmware.isEnable')" align="center" prop="isEnable">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isEnable" active-value="1" inactive-value="0"
                     @change="handleEnableChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.table.operate')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['app:firmwareVersion:edit']">{{$t('common.button.edit')}}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['app:firmwareVersion:remove']">{{$t('common.button.remove')}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改app固件版本管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item :label="$t('version.firmware.versionName')" prop="versionName">
          <el-input v-model="form.versionName" :placeholder="$t('version.firmware.placeholder.versionName')" />
        </el-form-item>
        <el-form-item :label="$t('version.firmware.versionNumber')" prop="versionNumber">
          <el-input v-model="form.versionNumber" :placeholder="$t('version.firmware.placeholder.versionNumber')" />
        </el-form-item>
        <el-form-item :label="$t('ota.version.versionType')" prop="versionType">
          <el-select v-model="form.versionType" :placeholder="$t('ota.version.placeholder.versionType')" :style="{ width: '100%' }">
            <el-option v-for="dict in dict.type.firmware_type" :key="dict.value" :label="dict.label"
                       :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('version.firmware.versionUrl')" prop="versionUrl">
          <el-upload class="upload-demo" drag accept=".bin" :limit="1" :headers="upload.headers"
                     :file-list="fileList"
                     :action="upload.url" multiple :on-success='handleFileSuccess' :on-progress="handleFileUploadProgress" :data="form"
                     drag :auto-upload="true">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">{{$t('version.firmware.uploadText')}}
              <em>{{$t('version.firmware.clickUpload')}}</em></div>
            <div class="el-upload__tip" slot="tip" style="color: red;">{{$t('version.firmware.uploadCheck')}}</div>
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t('version.firmware.remark')" prop="remark">
          <el-input v-model="form.remark" type="textarea" :placeholder="$t('version.firmware.placeholder.remark')" />
        </el-form-item>
        <el-form-item :label="$t('version.firmware.isForce')" prop="isForce">
            <el-radio-group v-model="form.isForce">
              <el-radio label="1">{{$t('version.firmware.yes')}}</el-radio>
              <el-radio label="0">{{$t('version.firmware.no')}}</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('version.firmware.isEnable')" prop="isEnable">
          <el-radio-group v-model="form.isEnable">
            <el-radio label="1">{{$t('version.firmware.yes')}}</el-radio>
            <el-radio label="0">{{$t('version.firmware.no')}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">{{$t('common.dialog.confirm')}}</el-button>
        <el-button @click="cancel">{{$t('common.dialog.cancel')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { listFirmwareVersion, getFirmwareVersion, delFirmwareVersion, addFirmwareVersion, updateFirmwareVersion, changeForce, changeEnable } from "@/api/version/firmware";

export default {
  name: "FirmwareVersion",
  dicts: ['phone_type','firmware_type'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // app固件版本管理表格数据
      firmwareVersionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        versionName: undefined,
        versionNumber: undefined,
        versionType: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        versionName: [
          { required: true, message: this.$t('version.firmware.rules.versionName'), trigger: "blur" }
        ],
        versionNumber: [
          { required: true, message: this.$t('version.firmware.rules.versionNumber'), trigger: "blur" }
        ],
        versionUrl: [
          { required: true, message: this.$t('version.firmware.rules.versionUrl'), trigger: "blur" }
        ],
        versionType: [
          { required: true, message: this.$t('version.firmware.rules.versionType'), trigger: "blur" }
        ],
        isForce: [
          { required: true, message: this.$t('version.firmware.rules.isForce'), trigger: "blur" }
        ],
        isEnable: [
          { required: true, message: this.$t('version.firmware.rules.isEnable'), trigger: "blur" }
        ],
      },
      upload: {
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/device/firmware/version/upload",
      },
      fileList: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询app固件版本管理列表 */
    getList() {
      this.loading = true;
      listFirmwareVersion(this.queryParams).then(response => {
        this.firmwareVersionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.fileList = [];
      this.form = {
        versionId: undefined,
        versionName: undefined,
        versionNumber: undefined,
        versionUrl: undefined,
        versionType: undefined,
        fileName: undefined,
        fileSize: undefined,
        remark: undefined,
        isForce: undefined,
        isEnable: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    handleForceChange(row) {
      let text = row.isForce === "0" ? this.$t('common.operate.tip.stop') : this.$t('common.operate.tip.enable');
      this.$modal.confirm(
        this.$t('common.message.tip.confirm', {
          operate: text,
          name: this.$t('version.firmware.isForce'),
          data: row.versionName
        })
      ).then(function () {
        return changeForce({ versionId: row.versionId, isForce: row.isForce });
      }).then(() => {
        this.$modal.msgSuccess(text + this.$t('common.operate.tip.success'));
        this.getList();
      }).catch(function () {
        row.isForce = row.isForce === "0" ? "1" : "0";
      });
    },
    handleEnableChange(row) {
      let text = row.isEnable === "0" ? this.$t('common.operate.tip.stop') : this.$t('common.operate.tip.enable');
      this.$modal.confirm(
        this.$t('common.message.tip.confirm', {
          operate: text,
          name: this.$t('version.firmware.isEnable'),
          data: row.versionName
        })
      ).then(function () {
        return changeEnable({ versionId: row.versionId, isEnable: row.isEnable });
      }).then(() => {
        this.$modal.msgSuccess(text + this.$t('common.operate.tip.success'));
        this.getList();
      }).catch(function () {
        row.isEnable = row.isEnable === "0" ? "1" : "0";
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.versionId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t('common.operate.type.add') + this.$t('version.firmware.moduleName');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const versionId = row.versionId || this.ids
      getFirmwareVersion(versionId).then(response => {
        this.loading = false;
        this.form = response.data;
        const uploadData = {
          name: response.data.fileName,
          url: response.data.versionUrl
        }
        this.fileList.push(uploadData)
        this.open = true;
        this.title = this.$t('common.operate.type.edit') + this.$t('version.firmware.moduleName');
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.versionId != null) {
            updateFirmwareVersion(this.form).then(response => {
              this.$modal.updateSuccess();
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addFirmwareVersion(this.form).then(response => {
              this.$modal.addSuccess();
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const versionIds = row.versionId || this.ids;
      const options = this.$t('common.message.tip.confirm', {
        operate: this.$t('common.operate.type.delete'),
        name: this.$t('version.firmware.versionId'),
        data: versionIds
      })
      this.$modal.confirm(options).then(() => {
        this.loading = true;
        return delFirmwareVersion(versionIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.deleteSuccess();
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },

    // 下面是文件上传功能
    handleFileSuccess(response, file) {
      this.form.versionUrl = response;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      this.form.fileSize = file.size
      this.form.fileName = file.name
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('app/firmware/version/export', {
        ...this.queryParams
      }, `firmware_version_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
